package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword()))
            return paramError;
        AdUser user = baseMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()), true);
        if (one == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
        if (s.equals(one.getPassword())) {
            one.setPassword("");
            one.setSalt("");
            String token = AppJwtUtil.getToken(one.getId().longValue());
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("user",one);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        } else return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "密码错误");

    }

    public static void main(String[] args) {
        String s = DigestUtils.md5DigestAsHex((2112 + "123456").getBytes());
        System.out.println(s);
    }
}
